package com.windward.vii.service;

import com.windward.vii.common.Constants;
import com.windward.vii.dao.entity.AssetUserAccount;
import com.windward.vii.dao.mapper.AssetUserAccountMapper;
import com.windward.vii.utils.rongcloud.RongCloudProxy;
import com.windward.vii.utils.ThreadPoolManager;
import com.windward.vii.utils.rongcloud.models.CodeSuccessResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AssetUserAccountService {

    private static Logger logger = LoggerFactory.getLogger(AssetUserAccountService.class);

    @Resource
    AssetUserAccountMapper assetUserAccountMapper;
    @Resource
    RongCloudProxy rongCloudProxy;

    public AssetUserAccount selectByUid(Long uid) {
        return assetUserAccountMapper.selectByUid(uid);
    }

    public boolean updateUserById(AssetUserAccount userAccount) {
        AssetUserAccount dbUser = assetUserAccountMapper.selectByUid(userAccount.getUid());
        if(dbUser != null) {
            // 修改头像，需要审核
            if(dbUser.getAvatar() != null && !dbUser.getAvatar().equals(userAccount.getAvatar())) {
                userAccount.setAvatarStatus(Constants.User.AVATAR_STATUS_INIT);
            }
        }
        int row = assetUserAccountMapper.updateByUidSelective(userAccount);
        if(row > 0) {
            asyncUpdateImNickname(userAccount);
        }
        return row > 0;
    }

    private void asyncUpdateImNickname(AssetUserAccount userAccount) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("connect: im.user.refresh, uid={}, nickname={}, avatar={}", userAccount.getUid(), userAccount.getNickname(), userAccount.getAvatar());
                    CodeSuccessResult messagePublishSystemResult = rongCloudProxy.getInstance().user.refresh(
                            String.valueOf(userAccount.getUid()),
                            userAccount.getNickname(),
                            userAccount.getAvatar());
                    logger.info("connect: im.user.refresh.result={}", messagePublishSystemResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public boolean updateOnlineStatusByUid(Long uid, Integer onlineStatus) {
        try {
            assetUserAccountMapper.updateOnlineStatusByUid(uid, onlineStatus);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
